const { By, until } = require('selenium-webdriver')

module.exports = function getRank (driver, appid) {
  const target = By.css('.rank-current table tbody .rank-double-wrap p:first-child')
  const defaultResult = {iphoneRank: '-', ipadRank: '-'};
  return driver.get(`https://www.qimai.cn/app/rank/appid/${appid}/country/cn`)
  .then(() => {
    return driver.wait(until.elementsLocated(target))
  })
  .then(async () => {
    const eles = await driver.findElements(By.css('.rank-current table thead tr th'))
    if (!eles) return defaultResult;
    const titleTasks = eles.map(ele => ele.getText())
    const titles = await Promise.all(titleTasks)
    let index = 0
    let hasRank = false
    for (;index < titles.length; index += 1) {
      if (typeof titles[index] === 'string' && titles[index].search('教育榜') >= 0 ) {
        hasRank = true;
        break;
      }
    }
    if (!hasRank) return defaultResult;
    const ranks = await driver.findElements(target);
    const iPhoneRankEle = ranks[index - 1];
    const iPadRankEle = ranks[(index + titles.length - 2)];
    const [iphoneRank, ipadRank] = await Promise.all([iPhoneRankEle.getText(), iPadRankEle.getText()]);
    console.log('iphoneRank: ', iphoneRank);
    console.log('ipadRank: ', ipadRank);
    return { iphoneRank, ipadRank };
  })
  .catch(() => {
    return defaultResult;
  })
}